﻿namespace LogicStudio.Framework.UI.Utilidades
{
    using System;
    using System.ServiceModel.DomainServices.Client;

    public class ControladorConsultaAsincrona
    {
        public void Invocar<T>(DomainContext context4Query, EntityQuery<T> qry, EventHandler<EntityResultsArgs<T>> evt) where T : Entity
        {
            context4Query.Load<T>(qry, LoadBehavior.RefreshCurrent, r =>
            {
                if (evt != null)
                {
                    try
                    {
                        if (r.HasError)
                        {
                            evt(this, new EntityResultsArgs<T>(r.Error));
                            r.MarkErrorAsHandled();
                        }
                        else
                        {
                            evt(this, new EntityResultsArgs<T>(r.Entities));
                        }
                    }
                    catch (Exception ex)
                    {
                        evt(this, new EntityResultsArgs<T>(ex));
                    }
                }
            }, null);

        }
    }
}